//
//  FSWHelperTool.m
//  HMT-APP
//
//  Created by 伏圣文 on 2017/8/25.
//  Copyright © 2017年 LXC. All rights reserved.
//

#import "FSWHelperTool.h"

@implementation FSWHelperTool



/**
 *  银行卡正则验证
 *
 *  @param bankCardNumber 银行卡号
 *
 *  @return Bool结果
 */
+ (BOOL) validateBankCardNumber: (NSString *)bankCardNumber{
    //    BOOL flag;
    if (bankCardNumber.length <= 0) {
        return NO;
    }
    //    NSString *regex2 = @"^(\\d{14,19})";
    //    NSPredicate *bankCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    //    return [bankCardPredicate evaluateWithObject:bankCardNumber];
    
    
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[bankCardNumber length];
    int lastNum = [[bankCardNumber substringFromIndex:cardNoLength-1] intValue];
    
    bankCardNumber = [bankCardNumber substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [bankCardNumber substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}
/**
 判断字符串是否位空
 @param inputString 输入字符串
 @returns 返回结果
 */
+(BOOL)stringNullOrEmpty:(NSString *)inputString
{
    if (inputString!=nil&&inputString.length>0) {
        return NO;
    }
    return YES;
}

+(BOOL)stringNotNumber:(NSString *)inputString
{
    NSCharacterSet *disallowedCharacters = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    NSRange foundRange = [inputString rangeOfCharacterFromSet:disallowedCharacters];
    if (foundRange.location != NSNotFound) {
        return YES;
    }
    return NO;
}
/*
 判断字符串是否为金额格式
 **/
+(BOOL)stringIsAmt:(NSString *)string{
    NSString *AMT = @"^(([0-9]|([1-9][0-9]{0,9}))((\\.[0-9]{1,2})?))$";
    NSPredicate *regexAmt = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", AMT];
    if ([regexAmt evaluateWithObject:string] == YES){
        return YES;
    }
    return NO;
    
}

/*
 判断字符串的每个字符是否为数字或字母
 @param string 输入字符串
 @returns 返回结果
 */

+(BOOL)containInvalidChar:(NSString *)inputString{
    
    NSCharacterSet *disallowedCharacters = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    NSRange foundRange = [inputString rangeOfCharacterFromSet:disallowedCharacters];
    if (foundRange.location != NSNotFound) {
        return YES;
    }
    return NO;
}

+(BOOL)isChinese:(NSString*)string{
    int strlength = 0;
    char* p = (char*)[string cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[string lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return ((strlength/2)==string.length)?YES:NO;
}

+(BOOL)isHaveChinese:(NSString *)string{
    BOOL result = NO;
    int length = (int)[string length];
    for (int i=0; i<length; ++i){
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [string substringWithRange:range];
        const char *cString = [subString UTF8String];
        if (strlen(cString) == 3){
            result = YES;
        }
    }
    return result;
}

+(BOOL)isContainsEmoji:(NSString *)string{
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 isEomji = YES;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    return isEomji;
}


+(BOOL)isValidCertId:(NSString *)string{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    int length =0;
    if (!string) {
        return NO;
    }else {
        length = (int)string.length;
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    NSString *valueStart2 = [string substringToIndex:2];
    BOOL areaFlag =NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    if (!areaFlag) {
        return false;
    }
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    int year =0;
    switch (length) {
        case 15:
            year = [string substringWithRange:NSMakeRange(6,2)].intValue +1900;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:string
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, string.length)];
            
            //            [regularExpression release];37131219920726532x
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            year = [string substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:string
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, string.length)];
            
            //[regularExpression release];
            
            if(numberofMatch >0) {
                int S = ([string substringWithRange:NSMakeRange(0,1)].intValue + [string substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([string substringWithRange:NSMakeRange(1,1)].intValue + [string substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([string substringWithRange:NSMakeRange(2,1)].intValue + [string substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([string substringWithRange:NSMakeRange(3,1)].intValue + [string substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([string substringWithRange:NSMakeRange(4,1)].intValue + [string substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([string substringWithRange:NSMakeRange(5,1)].intValue + [string substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([string substringWithRange:NSMakeRange(6,1)].intValue + [string substringWithRange:NSMakeRange(16,1)].intValue) *2 + [string substringWithRange:NSMakeRange(7,1)].intValue *1 + [string substringWithRange:NSMakeRange(8,1)].intValue *6 + [string substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M = @"F";
                NSString *JYM = @"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:[string substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return NO;
    }
}

#pragma mark 字符串金额处理
+(NSString *)processAmtDisplay:(NSString *)amtSTR{
    if(!amtSTR) {
        return (nil);
    }
    
    char a[30];
    bzero(a, sizeof(a));
    strcpy(a, [amtSTR UTF8String]);
    
    char *p = strchr(a, '.');
    while (p!=NULL && (p=p-3) > a) {
        char *pend = a + strlen(a);
        memmove(p+1, p, (pend-p)*sizeof(char));
        *p = ',';
    }
    
    NSString *processedSTR = [NSString stringWithUTF8String:a];
    return processedSTR;
}




/**
 *  拆分字符串为数组
 */
+(NSMutableArray *)getArrWithStr:(NSString *)valueStr{
    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSUInteger len = [valueStr length];
    for(NSUInteger i=0; i<len; i++){
        NSRange range = NSMakeRange(i, 1);
        [array addObject:[valueStr substringWithRange:range]];
    }
    return array;
}

/**
 *  拆分字符串为数组
 */
+(NSArray *)getArrWithStr:(NSString *)valueStr andKeyStr:(NSString *)keyStr{
    NSArray *array = [valueStr componentsSeparatedByString:keyStr];
    return array;
}


#pragma mark - 判断是否已成年
+ (BOOL)isManhoodWithCertID:(NSString *)certID
{
    NSRange range = NSMakeRange(6, 8);
    certID = [certID substringWithRange:range];
    
    NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
    dateF.dateFormat = @"YYYYMMdd";
    
    if ([certID hasPrefix:@"1988"]) {
        return YES;
    } else {
        //出生日期
        NSDate *burnDate = [dateF dateFromString:certID];
        
        //当前日期
        NSDate *dateNow = [NSDate date];
        
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
                                                   fromDate:burnDate
                                                     toDate:dateNow
                                                    options:0];
        if (components.year >= 18) {
            return YES;
        } else {
            return NO;
        }
    }
}

#pragma mark - 判断手机号码格式是否正确
+ (BOOL)isValidTelNum:(NSString *)telNum
{
    NSString * MOBILE = @"^[1][3-9][0-9]{9}$";
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    if ([regextestct evaluateWithObject:telNum] == YES) {
        return YES;
    } else {
        return NO;
    }
}

#pragma mark - 判断是否是中文用户名
+ (BOOL)validateNickname:(NSString *)nickname

{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{2,8}$";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    
    return [predicate evaluateWithObject:nickname];
}

#pragma mark - 判断是否为正整数
+ (BOOL)isPositiveInteger:(NSString *)number
{
    NSString *Regex = @"^[1-9]\\d*$";
    
    NSPredicate *PositiveIntegerPridi = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    
    return [PositiveIntegerPridi evaluateWithObject:number];
}


#pragma mark - 字符串前面添加空格
+ (NSString *)addSpace:(NSString *)string count:(int)count
{
    for (int i=0; i<count; i++) {
        string = [NSString stringWithFormat:@" %@", string];
    }
    return string;
}

#pragma mark - 将金额字段转换为货币格式
+ (NSString *)convertToCurrencyWith:(NSString *)string
{
    
    if (!string || [string isEqualToString:@""]) {
        return @"";
    }
    NSArray *strArr = [string componentsSeparatedByString:@"."];
    NSString *str1 = strArr[0];
    NSString *str2 = strArr[1];
    int count = 0;
    long long int a = str1.longLongValue;
    while (a != 0)
    {
        count++;
        a /= 10;
    }
    NSMutableString *resultStr = [NSMutableString stringWithString:str1];
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(resultStr.length - 3, 3);
        NSString *str = [resultStr substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [resultStr deleteCharactersInRange:rang];
    }
    [newstring insertString:resultStr atIndex:0];
    return [NSString stringWithFormat:@"%@.%@", newstring, str2];
}

#pragma mark -- 格式化浮点字符串
+ (NSString *)formatFloatString:(NSString *)string
{
    NSUInteger index = [string rangeOfString:@"."].location + 1;
    NSString *prefix = [string substringToIndex:index];
    NSString *suffix = [string substringFromIndex:index];
    if ([suffix isEqualToString:@"00"]) {
        return [NSString stringWithFormat:@"%d", (int)[string doubleValue]];
    } else {
        if ([[suffix substringFromIndex:1] isEqualToString:@"0"]) {
            return [NSString stringWithFormat:@"%@", [prefix stringByAppendingString:[suffix substringToIndex:1]]];
        } else {
            return [NSString stringWithFormat:@"%@", string];
        }
    }
}
#pragma mark -- 数组转json字符串
+ (NSString*)arrayToJson:(NSArray *)arr
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

+ (NSString*)modelToJson:(id)model
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:model options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

#pragma mark - 字典转json字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

#pragma mark - json字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        
        return nil;
    }
    return dic;
}
// model模型转字典 实现代码

+(NSDictionary*)dicFromObject:(NSObject*)object {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int count;
    objc_property_t * propertyList =class_copyPropertyList([object class], &count);
    for(int i =0; i < count; i++) {
        objc_property_t property = propertyList[i];
        const char * cName = property_getName(property);
        NSString * name = [NSString stringWithUTF8String:cName];
        NSObject*value = [object valueForKey:name];//valueForKey返回的数字和字符串都是对象
        if([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]]) {
            [dic setObject:value forKey:name];
        }else if([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
            //字典或字典
            [dic setObject:[self arrayOrDicWithObject:(NSArray*)value] forKey:name];
        }else if(value ==nil) {
            //null
            //[dic setObject:[NSNull null] forKey:name];//这行可以注释掉?????
        }else{
           //model
            [dic setObject:[self dicFromObject:value] forKey:name];
        }
    }
    return[dic copy];
    
}

//将可能存在model数组转化为普通数组

+(id)arrayOrDicWithObject:(id)origin {
    if([origin isKindOfClass:[NSArray class]]) {
    //数组
    NSMutableArray *array = [NSMutableArray array];
        for(NSObject * object in origin) {
            if([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
                [array addObject:object];
            }else if([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {
                [array addObject:[self arrayOrDicWithObject:(NSArray*)object]];
            }else{
                [array addObject:[self dicFromObject:object]];
                
            }
        }
        return [array copy];
        
    }else if([origin isKindOfClass:[NSDictionary class]]) {
    //字典
        NSDictionary * originDic = (NSDictionary*)origin;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for(NSString * key in originDic.allKeys) {
            id object = [originDic objectForKey:key];
            if([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]]) {
                [dic setObject:object forKey:key];
            }else if([object isKindOfClass:[NSArray class]] || [object isKindOfClass:[NSDictionary class]]) {
    //数组或字典
                [dic setObject:[self arrayOrDicWithObject:object] forKey:key];
                
            }else{//mode
                [dic setObject:[self dicFromObject:object] forKey:key];
            }
        }
        return [dic copy];
    }
    return [NSNull null];
}

#pragma mark -- 验证两位小数的字符串
+ (BOOL)validateMoneyFormat:(NSString *)moneyStr
{
    NSString* number=@"^[0-9]+(.[0-9]{1,2})?$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:moneyStr];
}



+(BOOL)checkLoginPassWord:(NSString *)password
{
    //6-20位数字和字母组成
    //    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSString *regex = @"^(?=.*[a-zA-Z0-9].*)(?=.*[a-zA-Z\\W].*)(?=.*[0-9\\W].*).{6,20}$";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:password] ;
}
#pragma mark - 判断是是否是六位数字
+ (BOOL)isPostCode:(NSString *)number
{
    NSString *Regex = @"^\\d{6}$";
    
    NSPredicate *PositiveIntegerPridi = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    
    return [PositiveIntegerPridi evaluateWithObject:number];
}


//根据身份证号获取生日
+(NSString *)birthdayStrFromIdentityCard:(NSString *)numberStr
{
    if (numberStr.length == 18 ) {
        NSMutableString *result = [NSMutableString stringWithCapacity:0];
        NSString *year = nil;
        NSString *month = nil;
        
        BOOL isAllNumber = YES;
        NSString *day = nil;
        if([numberStr length]<14)
            return result;
        
        //**截取前14位
        NSString *fontNumer = [numberStr substringWithRange:NSMakeRange(0, 13)];
        
        //**检测前14位否全都是数字;
        const char *str = [fontNumer UTF8String];
        const char *p = str;
        while (*p!='\0') {
            if(!(*p>='0'&&*p<='9'))
                isAllNumber = NO;
            p++;
        }
        if(!isAllNumber)
            return result;
        
        year = [numberStr substringWithRange:NSMakeRange(6, 4)];
        month = [numberStr substringWithRange:NSMakeRange(10, 2)];
        day = [numberStr substringWithRange:NSMakeRange(12,2)];
        
        [result appendString:year];
        [result appendString:@" 年 "];
        [result appendString:month];
        [result appendString:@" 月 "];
        [result appendString:day];
        [result appendString:@" 日 "];
        return result;
    }else{
        return @"快去实名认证吧";
    }
    
}
//根据身份证号性别
+(NSString *)getIdentityCardSex:(NSString *)numberStr
{
    if (numberStr.length == 18 ) {
        int sexInt=[[numberStr substringWithRange:NSMakeRange(16,1)] intValue];
        
        if(sexInt%2!=0)
        {
            return @"1";
        }
        else
        {
            return @"2";
        }
    }else{
        return @"0";
    }
    
}
//根据省份证号获取年龄
+(NSString *)getIdentityCardAge:(NSString *)numberStr
{
    
    NSDateFormatter *formatterTow = [[NSDateFormatter alloc]init];
    [formatterTow setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *bsyDate = [formatterTow dateFromString:[self birthdayStrFromIdentityCard:numberStr]];
    
    NSTimeInterval dateDiff = [bsyDate timeIntervalSinceNow];
    
    int age = trunc(dateDiff/(60*60*24))/365;
    
    return [NSString stringWithFormat:@"%d",-age];
}


/**
 *
 *String中过滤HTML标签
 *方法2
 */
+(NSString *)removeHTML2:(NSString *)html{
    NSArray *components = [html componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSMutableArray *componentsToKeep = [NSMutableArray array];
    for (int i = 0; i < [components count]; i = i + 2) {
        [componentsToKeep addObject:[components objectAtIndex:i]];
    }
    NSString *plainText = [componentsToKeep componentsJoinedByString:@""];
    return plainText;
}
/**
 *
 *String中过滤HTML标签
 *方法1
 */
+(NSString *)removeHTML:(NSString *)html {
    NSScanner *theScanner;
    NSString *text = nil;
    theScanner = [NSScanner scannerWithString:html];
    while ([theScanner isAtEnd] == NO) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text]withString:@" "];
    }
    return html;
}

//隐藏手机号
+(NSString *)mobileHide:(NSString *)mobile{
    if (mobile.length  == 11) {
        return [mobile stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }else{
        return mobile;
    }
}


//时间戳转字符串
+(NSString *)getDateString:(NSString *)numberStr withToTyp:(TimeStampOrDate)toType withStringType:(NSString *)stringType{
    //    numberStr = @"1504536557000";
    NSString* endDString = @"";
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    if (stringType == nil||[stringType isEqualToString:@""]) {
        [formatter setDateFormat:@"YYYY-MM-dd"];
    }else{
        [formatter setDateFormat:stringType];
    }
    
    if(toType == TimeStampToDate){
        NSDate *startD = [NSDate dateWithTimeIntervalSince1970:[numberStr longLongValue]/1000.0];
        endDString = [formatter stringFromDate:startD];
    }else if (toType == DateToTimeStamp){
        NSDate* date = [formatter dateFromString:numberStr]; //------------将字符串按formatter转成nsdate
        
        endDString = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    }
    return endDString;
}

//时间戳转data
+(NSDate *)getStringData:(NSString *)numberStr withToTyp:(TimeStampOrDate)toType withStringType:(NSString *)stringType{
    //    numberStr = @"1504536557000";
//    NSString* endDString = @"";
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    if (stringType == nil||[stringType isEqualToString:@""]) {
        [formatter setDateFormat:@"YYYY-MM-dd"];
    }else{
        [formatter setDateFormat:stringType];
    }
    NSDate *startD;
    if(toType == TimeStampToDate){
         startD = [NSDate dateWithTimeIntervalSince1970:[numberStr longLongValue]/1000.0];
    }else if (toType == DateToTimeStamp){
        startD = [formatter dateFromString:numberStr];
    }
    return startD;
}
//时间戳转字符串
+(NSString *)getMonthString:(NSString *)numberStr withStringType:(NSString *)stringType{
    NSString* endDString = @"";
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    if (stringType == nil||[stringType isEqualToString:@""]) {
        [formatter setDateFormat:@"YYYY-MM-dd"];
    }else{
        [formatter setDateFormat:stringType];
    }
//        NSDate *startD = [NSDate dateWithTimeIntervalSince1970:[numberStr longLongValue]];
    
    
    NSDate *startD = [formatter dateFromString:numberStr];
    NSDateFormatter *formatters = [[NSDateFormatter alloc]init];
    [formatters setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatters stringFromDate:startD]integerValue];
    endDString = [NSString stringWithFormat:@"%zd",currentMonth];
    return endDString;
}
+(NSString *)getMonthTimeString:(NSString *)numberStr withStringType:(NSString *)stringType{
    NSString* endDString = @"";
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    if (stringType == nil||[stringType isEqualToString:@""]) {
        [formatter setDateFormat:@"YYYY-MM-dd"];
    }else{
        [formatter setDateFormat:stringType];
    }
    NSDate *startD = [NSDate dateWithTimeIntervalSince1970:[numberStr longLongValue]];
    
    
    //    NSDate *startD = [formatter dateFromString:numberStr];
    NSDateFormatter *formatters = [[NSDateFormatter alloc]init];
    [formatters setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatters stringFromDate:startD]integerValue];
    endDString = [NSString stringWithFormat:@"%zd",currentMonth];
    return endDString;
}

/**
 base64 解码
 */
+(NSString *)getStringBaseEncoding:(NSString *)string{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; 
    
    id obj = [self dictionaryWithJsonString:str];
    NSString *attrsStr;
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict =(NSDictionary *)obj;
        attrsStr = [NSString stringWithFormat:@"%@ %@",dict[@"name"],dict[@"value"]];;
    }else if ([obj isKindOfClass:[NSArray class]]){
        NSArray *array = (NSArray *)obj;
        NSString *attrs =@"";
        for (NSDictionary *dict in array) {
            NSString *name =dict[@"name"];
            NSArray *value = dict[@"values"];
            NSString * att=@"";
            NSString *nstr = [NSString stringWithFormat:@"%@:",name];
            for (int i=0; i<value.count; i++) {
                NSString *str = value[i];
                NSString *vstr ;
                if (i==0) {
                     vstr = [NSString stringWithFormat:@"%@%@",nstr,str];
                }else{
                   vstr = [NSString stringWithFormat:@"、%@",str];
                }
                att = [NSString stringWithFormat:@"%@%@",att,vstr];
            }
            
            attrs = [NSString stringWithFormat:@"%@ %@",attrs,att];
        }
        attrsStr = attrs;
    }
    
    
    return attrsStr;
}

+(NSString *)getBaseToArrayEncoding:(NSString *)string{
NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *str1 = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSData *data1 = [[NSData alloc]initWithBase64EncodedString:str1 options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *str = [[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];
    
    id obj = [self dictionaryWithJsonString:str];
    NSString *attrs =@"";
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict =(NSDictionary *)obj;
        attrs = [NSString stringWithFormat:@"%@ %@",dict[@"name"],dict[@"value"]];;
    }else{
        NSArray *array = (NSArray *)obj;
        
        for (NSDictionary *dict in array) {
            NSString *name =dict[@"name"];
            NSString *value = dict[@"value"];
            NSString *nstr = [NSString stringWithFormat:@"%@:%@",name,value];
            attrs = [NSString stringWithFormat:@"%@ %@",attrs,nstr];
        }
    } 
    return attrs;
}
+(NSString *)getBaseStringEncoding:(NSString *)string{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    id obj = [self dictionaryWithJsonString:str];
    NSString *attrs =@"";
   
    for (NSDictionary *dict  in obj) {
        for (NSString *key in dict) {
            if (![key isEqual:@"count"]) {
                NSString *value = dict[key];
                attrs = [attrs stringByAppendingString:[NSString stringWithFormat:@"%@:%@ ",key,value]];
            }
        }
    }
   
    
    return attrs;
    
}


+(NSDictionary *)getBaseDictionaryEncoding:(NSString *)string{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    id obj = [self dictionaryWithJsonString:str];
  
    NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
    for (NSDictionary *dict  in obj) {
        for (NSString *key in dict) {
            NSString *value;
            NSString *name;
            if ([key isEqualToString:@"name"]) {
                 value = dict[key];
            }else{
                id values = dict[key];
                if ([values isKindOfClass:[NSArray class]]) {
                    NSArray * arr =(NSArray *)values;
                    name = arr[0];
                }
                name = values;
            }
            resultDict[value] = name;
        }
    }
    
    
    return resultDict;
    
}
+(NSDictionary *)getBaseddddDictionaryEncoding:(NSString *)string{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    id obj = [self dictionaryWithJsonString:str];
    
    NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
    for (NSDictionary *dict  in obj) {
        for (NSString *key in dict) {
           NSString *values = dict[key];
            resultDict[key] = values;
        }
    }
    
    
    return resultDict;
    
}


+(NSDictionary *)getBaseEncoding:(NSString *)string{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *dict = [self dictionaryWithJsonString:str];
    return dict;
    
}

+(NSString *)base64EncodedString:(NSDictionary *)dict
{
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    return [data base64EncodedStringWithOptions:0];
}
+(NSString *)base64ArrayEncodedString:(NSArray *)array
{
    NSData *data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    
    return [data base64EncodedStringWithOptions:0];
}


+(NSMutableAttributedString *)textStrLastColor:(NSString *)str andColor:(UIColor *)color andFontSize:(float)size andLength:(NSInteger)length{
    NSMutableAttributedString *fontAttributeNameStr = [[NSMutableAttributedString alloc]initWithString:str];
    // 2.添加属性
    if (size > 0) {
        [fontAttributeNameStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:size] range:NSMakeRange(str.length - length, length)];
    }
    [fontAttributeNameStr addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(str.length - length, length)];
    
    return fontAttributeNameStr;
}

#pragma mark -- 判断字符串中是否含有某个字符串
+ (BOOL)stringRoaldSearch:(NSString *)str withString:(NSString*)title
{
    if([str rangeOfString:title].location !=NSNotFound)//_roaldSearchText
    {
       return YES;
    }
    else
    {
        return NO;
    }
}

+(BOOL)isFringe{
    
    if (StatusBarHeight == 44 ||StatusBarHeight == 47) {
        return YES;
    }
    return NO;
}


+(NSString*)getCurrentTimes:(NSString *)dateFormat{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    if ([dateFormat isEqualToString:@""]) {
         [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    }else{
         [formatter setDateFormat:dateFormat];
    }
    
   
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
   
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}

+(NSDate*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    //现在时间,你可以输出来看下是什么格式
    NSDate *datenow = [NSDate date];
    //----------将nsdate按formatter格式转成nsstring
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSDate *date = [formatter dateFromString:currentTimeString];
    return date;
    
}

//获取当前时间戳有两种方法(以秒为单位)

+(NSString *)getNowTimeTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
  
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    
    
    
    return timeSp;
    
}

//字符串时间转字符串
+(NSString *)getStringToStringTimestamp:(NSString *)dateStr andFormatter:(NSString *)format{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (format.length > 0) {
        [dateFormatter setDateFormat:format];
    }else{
        [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    }
    //下面以 '2017-04-24 08:57:29'为例代表服务器返回的时间字符串
    NSDate *date = [dateFormatter dateFromString:dateStr];
    
    
    
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    if (format.length <= 0) {
        [dateFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    }else{
        [dateFormat setDateFormat:format];
    }
    NSString *oneDayStr = [dateFormat stringFromDate:date];
    
    return oneDayStr;
}

//字符串时间转date
+(NSDate*)getNowTimeTimestamp:(NSString *)dateStr{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    //下面以 '2017-04-24 08:57:29'为例代表服务器返回的时间字符串
    NSDate *date = [dateFormatter dateFromString:dateStr];
    
    return date;
}
//date转字符串时间
+(NSDate*)getStrToDate:(NSString *)dateStr andFormatter:(NSString *)format{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (format.length <= 0) {
        [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    }else{
        [dateFormatter setDateFormat:format];
    }
    NSDate *date = [dateFormatter dateFromString:dateStr];
    return date;
}

//date转字符串时间
+(NSString*)getDateToStr:(NSDate *)date andFormatter:(NSString *)format{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (format.length <= 0) {
        [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    }else{
        [dateFormatter setDateFormat:format];
    }
    NSString *oneDayStr = [dateFormatter stringFromDate:date];
    return oneDayStr;
}

//时间比较
+ (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"oneDay : %@, anotherDay : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //在指定时间前面 过了指定时间 过期
        NSLog(@"oneDay  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //没过指定时间 没过期
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //刚好时间一样.
    //NSLog(@"Both dates are the same");
    return 0;
    
}

//时间比较
+ (int)compareOneDay:(NSString *)oneDay withAnotherDay:(NSString *)anotherDay andDateFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if ([dateFormat isEqualToString:@""]) {
         [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    }else{
         [dateFormatter setDateFormat:dateFormat];
    }
     
    NSDate *dateA = [dateFormatter dateFromString:oneDay];
    NSDate *dateB = [dateFormatter dateFromString:anotherDay];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"oneDay : %@, anotherDay : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //在指定时间前面 过了指定时间 过期
        NSLog(@"oneDay  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //没过指定时间 没过期
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //刚好时间一样.
    //NSLog(@"Both dates are the same");
    return 0;
    
}

//指定日期是周几
+ (NSString*)weekDayStr:(NSString*)format{
    
    NSString *weekDayStr = nil;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    if(format.length>=10) {
        NSString *nowString = [format substringToIndex:10];
        NSArray *array = [nowString componentsSeparatedByString:@"-"];
        if(array.count==0) {
            array = [nowString componentsSeparatedByString:@"/"];
        }
        
        if(array.count>=3) {
            NSInteger year = [[array objectAtIndex:0] integerValue];
            NSInteger month = [[array objectAtIndex:1] integerValue];
            NSInteger day = [[array objectAtIndex:2] integerValue];
            [comps setYear:year];
            [comps setMonth:month];
            [comps setDay:day];
        }
    }
    //日历
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    //获取传入date
    NSDate *_date = [gregorian dateFromComponents:comps];
    
    NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:_date];
    NSInteger week = [weekdayComponents weekday];
    switch(week) {
        case 1:
            weekDayStr =@"星期日";
            break;
        case 2:
            weekDayStr =@"星期一";
            break;
        case 3:
            weekDayStr =@"星期二";
            break;
        case 4:
            weekDayStr =@"星期三";
            break;
        case 5:
            weekDayStr =@"星期四";
            break;
        case 6:
            weekDayStr =@"星期五";
            break;
        case 7:
            weekDayStr =@"星期六";
            break;
        default:
            weekDayStr =@"";
            break;
    }
    return weekDayStr;
}


//指定日期是周几
+ (NSInteger)weekDayInt:(NSString*)format{
    
    NSInteger weekDayInt = 1;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    if(format.length>=10) {
        NSString *nowString = [format substringToIndex:10];
        NSArray *array = [nowString componentsSeparatedByString:@"-"];
        if(array.count==0) {
            array = [nowString componentsSeparatedByString:@"/"];
        }
        
        if(array.count>=3) {
            NSInteger year = [[array objectAtIndex:0] integerValue];
            NSInteger month = [[array objectAtIndex:1] integerValue];
            NSInteger day = [[array objectAtIndex:2] integerValue];
            [comps setYear:year];
            [comps setMonth:month];
            [comps setDay:day];
        }
    }
    //日历
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    //获取传入date
    NSDate *_date = [gregorian dateFromComponents:comps];
    
    NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:_date];
    NSInteger week = [weekdayComponents weekday];
    switch(week) {
        case 1:
            weekDayInt = 7;
            break;
        case 2:
            weekDayInt = 1;
            break;
        case 3:
            weekDayInt = 2;
            break;
        case 4:
            weekDayInt = 3;
            break;
        case 5:
            weekDayInt = 4;
            break;
        case 6:
            weekDayInt = 5;
            break;
        case 7:
            weekDayInt = 6;
            break;
        default:
            weekDayInt = 0;
            break;
    }
    return weekDayInt;
}
//获取前月的第一天与最后一天
+ (NSArray *)getMonthFirstAndLastDayWith:(NSString *)dateStr{
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY-MM-dd"];
    NSDate *newDate=[format dateFromString:dateStr];
    double interval = 0;
    NSDate *firstDate = nil;
    NSDate *lastDate = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];

    BOOL OK = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:& firstDate interval:&interval forDate:newDate];
    
    if (OK) {
        lastDate = [firstDate dateByAddingTimeInterval:interval - 1];
    }else {
        return @[@"",@""];
    }

    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *firstString = [myDateFormatter stringFromDate: firstDate];
    NSString *lastString = [myDateFormatter stringFromDate: lastDate];
    return @[firstString, lastString];
}


+ (NSString *)getMonthFirstDayWithDate:(NSDate *)date format:(NSString *)aformat{
    NSDate *newDate = date;
    double interval = 0;
    NSDate *firstDate = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    BOOL bl = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:& firstDate interval:&interval forDate:newDate];
    if (bl) {
        NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
        [myDateFormatter setDateFormat:aformat];
        NSString *firstString = [myDateFormatter stringFromDate: firstDate];
        return firstString;
    }
    return @"";
}
+ (NSString *)getMonthLastDayWithDate:(NSDate *)date format:(NSString *)aformat{
    NSDate *newDate = date;
    double interval = 0;
    NSDate *firstDate = nil;
    NSDate *lastDate = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    BOOL bl = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:& firstDate interval:&interval forDate:newDate];
    if (bl) {
        lastDate = [firstDate dateByAddingTimeInterval:interval - 1];
        NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
        [myDateFormatter setDateFormat:aformat];
        NSString *lastString = [myDateFormatter stringFromDate: lastDate];
        return lastString;
    }
    return @"";
}

//获取前周的第一天与最后一天
+ (NSArray *)getZhouLastDayWithDate{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitDay
                                           fromDate:now];

    // 得到星期几
    // 1(星期天) 2(星期二) 3(星期三) 4(星期四) 5(星期五) 6(星期六) 7(星期天)
    NSInteger weekDay = [comp weekday]-1;
    // 得到几号
    NSInteger day = [comp day];

//    NSLog(@"weekDay:%ld   day:%ld",weekDay,day);

    // 计算当前日期和这周的星期一和星期天差的天数
    long firstDiff,lastDiff;
    if (weekDay == 1) {
        firstDiff = 1;
        lastDiff = 0;
    }else{
        firstDiff = [calendar firstWeekday] - weekDay;
        lastDiff = 7 - weekDay;
    }

//    NSLog(@"firstDiff:%ld   lastDiff:%ld",firstDiff,lastDiff);

    // 在当前日期(去掉了时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek= [calendar dateFromComponents:firstDayComp];

    NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek= [calendar dateFromComponents:lastDayComp];

    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"YYYY-MM-dd"];
//    NSLog(@"星期一开始 %@",[formater stringFromDate:firstDayOfWeek]);
//    NSLog(@"当前 %@",[formater stringFromDate:now]);
//    NSLog(@"星期天结束 %@",[formater stringFromDate:lastDayOfWeek]);
    NSString *firstString = [formater stringFromDate:firstDayOfWeek];
    NSString *lastString = [formater stringFromDate:lastDayOfWeek];
    return @[firstString, lastString];
     
       
}

//获取单个年月日
+(NSString *)getDataOneYearOrMonthOrDay:(NSInteger)number {
    NSDate *date = [NSDate date];
    //下面是单独获取每项的值
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
    
    comps = [calendar components:unitFlags fromDate:date];
    switch (number) {
        case 0:{
            //年
            float year=[comps year];
            return  [self getNumString:year];
            break;
        }
        case 1:{
            //月
            float month = [comps month];
            return [self getNumString:month];
            break;
        }
        case 2:{
            //日
            float day = [comps day];
           return [self getNumString:day];
            break;
        }
        case 3:{
            //时
            float hour = [comps hour];
            return [NSString stringWithFormat:@"%f",hour];
            break;
        }
        case 4:{
            //分
            float minute = [comps minute];
            return [NSString stringWithFormat:@"%f",minute];
            break;
        }
        case 5:{
            //秒
            float second = [comps second];
            return [NSString stringWithFormat:@"%f",second];
            break;
        }
        default:{
            //星期 注意星期是从周日开始计算
            float week = [comps weekday];
            return [NSString stringWithFormat:@"%f",week];
            break;
        }
    }
}

//获取指定日期的单个年月日
+(NSString *)getDataOneYearOrMonthOrDay:(NSDate *)datetime andNumber:(NSInteger)number {
    NSDate *date;
    if (datetime == nil) {
        date = [NSDate date];
    }else{
//        NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
//        [inputFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//        date = [inputFormatter dateFromString:datetime];
        
        date = datetime;
    }
     
    //下面是单独获取每项的值
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
    
    comps = [calendar components:unitFlags fromDate:date];
    switch (number) {
        case 0:{
            //年
            float year=[comps year];
            return [NSString stringWithFormat:@"%.0f",year];
            break;
        }
        case 1:{
            //月
            float month = [comps month];
            return [self getNumString:month];
            break;
        }
        case 2:{
            //日
            float day = [comps day];
            return [self getNumString:day];
            break;
        }
        case 3:{
            //时
            float hour = [comps hour];
            return [NSString stringWithFormat:@"%.0f",hour];
            break;
        }
        case 4:{
            //分
            float minute = [comps minute];
            return [NSString stringWithFormat:@"%.0f",minute];
            break;
        }
        case 5:{
            //秒
            float second = [comps second];
            return [NSString stringWithFormat:@"%.0f",second];
            break;
        }
        default:{
            //星期 注意星期是从周日开始计算
            float week = [comps weekday];
            return [NSString stringWithFormat:@"%.0f",week];
            break;
        }
    }
}

+(NSString *)getNumString:(float)num{
    NSString *str = @"";
    if (num < 10) {
        str = [NSString stringWithFormat:@"0%.0f",num];
    }else{
         str = [NSString stringWithFormat:@"%.0f",num];
    }
    return str;
}



//获取指定日期的单个年月日 无0
+(NSString *)getNoODataOneYearOrMonthOrDay:(NSDate *)datetime andNumber:(NSInteger)number {
    NSDate *date;
    if (datetime == nil) {
        date = [NSDate date];
    }else{
        
        date = datetime;
    }
     
    //下面是单独获取每项的值
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
    
    comps = [calendar components:unitFlags fromDate:date];
    switch (number) {
        case 0:{
            //年
            float year=[comps year];
            return [NSString stringWithFormat:@"%.0f",year];
            break;
        }
        case 1:{
            //月
            float month = [comps month];
            return [NSString stringWithFormat:@"%.0f",month];
            break;
        }
        case 2:{
            //日
            float day = [comps day];
            return [NSString stringWithFormat:@"%.0f",day];
            break;
        }
        case 3:{
            //时
            float hour = [comps hour];
            return [NSString stringWithFormat:@"%.0f",hour];
            break;
        }
        case 4:{
            //分
            float minute = [comps minute];
            return [NSString stringWithFormat:@"%.0f",minute];
            break;
        }
        case 5:{
            //秒
            float second = [comps second];
            return [NSString stringWithFormat:@"%.0f",second];
            break;
        }
        default:{
            //星期 注意星期是从周日开始计算
            float week = [comps weekday];
            return [NSString stringWithFormat:@"%.0f",week];
            break;
        }
    }
}

//获取时间差
+ (float)pleaseInsertStarTime:(NSString *)starTime andInsertEndTime:(NSString *)endTime andType:(NSInteger)type andFormat:(NSString *)format{
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    if (format.length > 0) {
        [formater setDateFormat:format];//根据自己的需求定义格式
    }else{
        [formater setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//根据自己的需求定义格式
    }
    NSDate* startDate = [formater dateFromString:starTime];
    NSDate* endDate = [formater dateFromString:endTime];
    NSTimeInterval timeInterval = [endDate timeIntervalSinceDate:startDate];
    float time = 0;
    if (type == 0) {
//        秒
        time = timeInterval;
    }else if (type == 1){
//        分
        time = timeInterval / 60;
    }else if (type == 2){
//        时
        time = timeInterval / 60 /60;
    }
    
    return time;
}

//指定时间的前几天或者后几天
+(NSString *)getBeforeOrAfterDate:(NSString *)datetime andFormat:(NSString *)formet andBAType:(DateTimeDayBAType)type andDay:(int)day{ 
    int days = day;    // n天的天数
    NSDate *appointDate;    // 指定日期声明
    NSTimeInterval oneDay = 24 * 60 * 60;  // 一天一共有多少秒
    NSDate *currentDate ;
    if (datetime == nil|| [datetime isEqualToString:@""]) {
         currentDate = [NSDate date];
    }else{
//        NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
//        [inputFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];
//        currentDate = [inputFormatter dateFromString:datetime];
        
        NSDateFormatter* inputFormatter = [[NSDateFormatter alloc] init];
        inputFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
        [inputFormatter setDateFormat:@"YYYY-MM-dd"];//根据自己的需求定义格式
        currentDate = [inputFormatter dateFromString:[NSString stringWithFormat:@"%@",datetime]];
    }
    
    if (type == DateTimeDayAfter) {
        appointDate = [currentDate dateByAddingTimeInterval: oneDay * days];
    }else{
        appointDate = [currentDate dateByAddingTimeInterval: -(oneDay * days)];
    }
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    if (formet == nil||[formet isEqualToString:@""]) {
        [formatter setDateFormat:@"YYYY-MM-dd"];
    }else{
        [formatter setDateFormat:formet];
    }
    return [formatter stringFromDate:appointDate];
}
//替换指定字符串
+(NSString *)stringByReplacingOccurrencesOfString:(NSString *)oldStr andStartStr:(NSString *)startStr andEndStr:(NSString *)endStr{
    NSString *newStr = [oldStr stringByReplacingOccurrencesOfString:startStr withString:endStr];
    return newStr;
}

/**
 *判断字符串是否为空
 */
+  (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES; 
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
        
    }     return NO;
}
//nil to ""
+(NSString *)isBlankToString:(NSString *)string {
    if (string == nil || string == NULL) {
        return @"";
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return @"";
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return @"";
        
    }
    return string;
}

//nil to "0"
+(NSString *)isBlankTo0String:(NSString *)string {
    if (string == nil || string == NULL) {
        return @"0";
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return @"0";
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return @"0";
        
    }
    return string;
}

//nil to str
+(NSString *)isBlankToString:(NSString *)string andToString:(NSString *)tostr{
    if (string == nil || string == NULL) {
        return tostr;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return tostr;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return tostr;
        
    }
    return string;
}

+(NSString *)fromUrlGetAppoint:(NSString *)urlString andAppointStr:(NSString *)appoint{
    NSURL *url = [NSURL URLWithString:urlString];
    NSArray *urlArray = [[url absoluteString] componentsSeparatedByString:@"&"];
    NSString *num = @"";
    NSString *appointstr = [NSString stringWithFormat:@"%@=",appoint];
    for (int i = 0; i<urlArray.count; i++) {
        NSString *str = urlArray[i];
        if ([self stringRoaldSearch:str withString:appointstr]) {
            NSArray *numArray = [str componentsSeparatedByString:@"="];
            for(int j = 0; j < numArray.count; j++){
                NSString *numstr = numArray[j];
                if ([numstr isEqualToString:appoint]) {
                    if (numArray.count == 2) {
                        if (j+1 < numArray.count) {
                            num =  numArray[j+1];
                            num = [num stringByRemovingPercentEncoding];
                        }
                    }
                }
            }
        }
    }
    return num;
}


/**
 *去除<br><P>标签
 */
+(NSString *)stringHtmlBrClear:(NSString *)str{
    NSString *newStr = [str stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
    newStr = [newStr stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
    newStr = [newStr stringByReplacingOccurrencesOfString:@"<p>" withString:@""];
    newStr = [newStr stringByReplacingOccurrencesOfString:@"</p>" withString:@""];
    return [NSString stringWithFormat:@"%@",newStr];
}
 
@end
